package com.jfm.jfmm.utils;

import cn.hutool.script.JavaScriptEngine;
import cn.hutool.script.ScriptUtil;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

/**
 * @author DYang
 * @since 2024-10-29 22:13
 *
 * 描述：使用JS 引擎计算获取数据
 */
public class JavaScriptUtil {

    private static final ScriptEngine engine;

    static {
        ScriptEngineManager manager = new ScriptEngineManager();
        engine = manager.getEngineByName("JavaScript");
    }

    /**
     * 执行js代码
     * @param js 简单计算函数
     * @return
     * @throws ScriptException
     */
    public static Object execute(String js) throws ScriptException {
        return engine.eval(js);
    }

    /**
     * 执行js代码
     * @param js 简单计算函数
     * @param params 参数
     * @return
     * @throws ScriptException
     * @throws NoSuchMethodException
     */
    public static Object execute(String js,Object ... params) throws ScriptException, NoSuchMethodException {
        ScriptEngineManager sem = new ScriptEngineManager();
        ScriptEngine engine = sem.getEngineByExtension("js");
        Invocable invocable = (Invocable) engine;
        return invocable.invokeFunction(js,params);
    }

    public static void main(String[] args) throws ScriptException, NoSuchMethodException {
        ScriptEngineManager sem = new ScriptEngineManager();
        //查找并为给定的扩展创建ScriptEngine。也可用getEngineByName，查找并为给定名称创建ScriptEngine
        ScriptEngine jsEngine = sem.getEngineByExtension("js");
        try {
            Object eval = jsEngine.eval("1 + 1");
            System.out.println(eval);
        } catch (ScriptException e) {
            e.printStackTrace();
        }
    }

}

